package repository.impl;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import repository.ProfileRepository;
import domain.Profile;
import domain.User;
import domain.exceptions.DuplicateException;


@Repository
public class ProfileRepositoryImpl extends AbstractHibernateRepository<Profile> implements ProfileRepository{

	@Autowired
	public ProfileRepositoryImpl(SessionFactory sessionfactory){
		super(sessionfactory);
	}
	
	public boolean existsProfile(Profile profile) {
		String hql = "FROM Profile as p WHERE p.user=?";
		List<Profile> result = find(hql, profile.getUser());
		return !result.isEmpty();
	}
	
	public void newProfile(Profile profile) throws DuplicateException{
		if (existsProfile(profile)) {
			throw new DuplicateException();
		}
		save(profile);
	}

	public Profile getProfileByUser(User user) {
		String hql = "FROM Profile WHERE user.docnumber=?";
		List<Profile> result = find(hql, user.getDocNumber());
		return result.isEmpty() ? null : result.get(0);
	}
	
	public Profile getProfile(int id) {
		return get(Profile.class, id);
	}
	
}